package cn.michael.dev.sort;

/**
 * Created by hufenggang on 2021/8/31.
 *
 * 归并排序算法
 */
public class MergeSort {

    public void mergeSort(int[] array, int n) {
        mergeSortInternally(array, 0, n - 1);
    }

    private static void mergeSortInternally(int[] a, int p, int r) {
        // 递归终止条件
        if (p >= r) {
            return;
        }
        // 获取p到r之间的中间位置q，防止(q+r)的和超过int类型最大值
        int q = p + (r -p) / 2;
        // 分治递归
        mergeSortInternally(a, p , q);
        mergeSortInternally(a, q + 1, r);

        merge(a, p, q, r);
    }

    private static void merge(int[] a, int p, int q, int r) {
        // 初始化变量i, j, k
        int i = p;
        int j = q + 1;
        int k = 0;

        int[] tmp = new int[r - p +1];
        while (i <= q && j <= r) {
            if (a[i] <= a[j]) {
                tmp[k++] = a[i++];
            } else {
                tmp[k++] = a[j++];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 5, 4, 1, 2, 6};
        MergeSort mergeSort = new MergeSort();
        mergeSort.mergeSort(arr, arr.length);

        for(int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
